package com.cc.controller;

import com.cc.entity.Employee;
import com.cc.entity.R;
import com.cc.enums.HttpEnum;
import com.cc.service.EmployeeService;
import com.cc.util.FileUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("employee")
@CrossOrigin
@ResponseBody
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    @GetMapping
    //查询所有员工
    public List<Employee> getList() {
        return employeeService.getList();
    }

    @PostMapping
    //添加员工
        public R addEmployee(Employee employee, MultipartFile bookImageFile, HttpServletRequest request) {
            //todo 默认设置书籍类型为1
            employee.setEmployeeId(1);
            // 得到上传图片的地址
            String imgPath;
            try {
                //ImageUtil为之前添加的工具类
                imgPath = FileUtil.upload(request, bookImageFile);
                if (imgPath != null) {
                    // 将上传图片的地址封装到实体类
                    employee.setImagePath(imgPath);
                    System.out.println("-----------------图片上传成功！");
                } else {
                    System.out.println("-----------------图片上传失败！");
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("----------------图片上传失败！");
            }
            int count = employeeService.addEmployee(employee);

            return count > 0 ? R.success("员工新增成功") : R.fail(HttpEnum.ERROR.getCode(),"员工新增失败");
        }
    @GetMapping("page")
    public PageInfo<Employee> getPage(Integer pageNum){
        PageInfo<Employee> pageInfo = employeeService.getPage(pageNum);
        return pageInfo;
    }
}